package com.luis.toolsuite.util;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.luis.toolsuite.downsampling.model.DataPoint;

public class Helper {

	public static final int TOTAL_SIZE = 10000;
	public static final int BUCKET = 400;
	private Helper() {}
	
	public static List<List<DataPoint>> split(List<DataPoint> original){
		int pointPerBucket = (original.size()-2) /(BUCKET-2);
		List<List<DataPoint>> bucketList = new ArrayList<>();
		bucketList.add(original.subList(0, 1));
		int from = 1;
		for(int i=1;i<BUCKET-1;i++) {
			int to = from + pointPerBucket;
			if(to > original.size()-1 || i== BUCKET-2) {
				to = original.size()-1;
			}
			List<DataPoint> bucket = original.subList(from, to);
			bucketList.add(bucket);
			from = to;
		}
		bucketList.add(original.subList(original.size()-1,original.size()));
		return bucketList;
	}

	public static DataPoint getModePoint(List<DataPoint> bucket) {
		//TODO 累积损伤模型不适用，暂时没有实现
		return null;
	}
	
	public static DataPoint getMedianPoint(List<DataPoint> bucket) {
		int size = bucket.size();
		if(size % 2 == 0) return bucket.get(size/2 -1);		
		return bucket.get((size-1)/2);
	}
	//获取最大三角形面积的点
	public static DataPoint getLargetTriangelPoint(DataPoint first, DataPoint last, List<DataPoint> dataset) {
		BigDecimal area = BigDecimal.ZERO;
		DataPoint maxPoint = null;
		for(DataPoint p: dataset) {
			BigDecimal tempArea = calcTriangleArea(first,last,p);
			if(tempArea.compareTo(area) > 0) {
				area = tempArea;
				maxPoint = p;
			} 
				
		}
		return maxPoint;
	}
	
	public static BigDecimal calcTriangleArea(DataPoint p1,DataPoint p2,DataPoint p3) {
		BigDecimal fx = BigDecimal.valueOf(p1.getTime());
		BigDecimal fy = BigDecimal.valueOf(p1.getScore());
		BigDecimal lx = BigDecimal.valueOf(p2.getTime());
		BigDecimal ly = BigDecimal.valueOf(p2.getScore());
		BigDecimal mx = BigDecimal.valueOf(p3.getTime());
		BigDecimal my = BigDecimal.valueOf(p3.getScore());
		return fx.multiply(my.subtract(ly).abs()).add(
				mx.multiply(fy.subtract(ly).abs())).add(
						lx.multiply(fy.subtract(my).abs()));
	}
	
	public static void print(List<DataPoint> result) {
		result.stream().forEach(p->{
			System.out.println(p.getTime());
		});
	}
}
